package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            Socket clientSocket = serverSocket.accept();
            Thread t = new Thread(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
//            processConnection在使用后没有进行close是不科学的
//            所以在try后面加finally，close


        }
    }

//    通过一个方法来处理一个连接
    private void processConnection(Socket clientSocket) throws IOException {
//        1.打印一个日志，当前客户端连上
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
//        2.从socket中获取到流对象，来进一步后续操作
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
//            3.搞个循环，针对每一个连接，客户端可能会发送多个请求，服务器也需要返回多个响应
            Scanner scanner = new Scanner(System.in);
            while (true){
//                3.1读取请求并解析
                if (!scanner.hasNext()){
//                    如果发现后续没有数据了，就说明TCP的连接已经断开
                    System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
//                3.2根据请求计算响应
                String response = process(request);
//                3.3把响应写回给客户端
                outputStream.write(response.getBytes(),0,response.getBytes().length);
//                3.4服务器打印日志
                System.out.printf("[%s:%d] req=%s,resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();
        }
    }

//    根据请求计算响应
//    由于是回显服务器，直接把请求作为响应返回去
    private String process(String request) {
//        给响应后面加个换行符，使得客户端读取响应式也有明确的分隔符
        return request+"\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
